package drz.oddb;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;

import drz.oddb.Memory.*;
import drz.oddb.Transaction.SystemTable.BiPointerTable;
import drz.oddb.Transaction.SystemTable.ClassTable;
import drz.oddb.Transaction.SystemTable.ClassTableItem;
import drz.oddb.Transaction.SystemTable.DeputyTable;
import drz.oddb.Transaction.SystemTable.ObjectTable;
import drz.oddb.Transaction.SystemTable.SwitchingTable;
import drz.oddb.Transaction.TransAction;
import drz.oddb.show.PaintT;

public class MainActivity extends AppCompatActivity {

    //查询输入框

    private EditText editText;

    private TextView text_view;
    TransAction trans = new TransAction(this);
    Intent music = null;

    private String unionPathName = "paths";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        music = new Intent(MainActivity.this,MusicServer.class);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //播放BGM
        startService(music);

        //查询按钮
        Button button = findViewById(R.id.button);
        editText = findViewById(R.id.edit_text);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //onStop();
                //trans.Test();
               trans.query(editText.getText().toString());
            }
        });

        //退出按钮
        Button exit_button = findViewById(R.id.exit_button);
        exit_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showexitdialog(v);
                stopService(music);
            }
        });

        //展示按钮
        Button show_button = findViewById(R.id.showbutton);
        show_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //onStop();
                trans.PrintTab();
            }
        });

        // test 按钮
        Button test_button = findViewById(R.id.testbutton);
        test_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "You clicked Test Button", Toast.LENGTH_SHORT).show();
                // TODO: open device file explore and upload files in datasets
                String dirName = getResources().getString(R.string.dir_name);
                double[][] baidu        = split(readTextFile(dirName + "/dataset/baidu.txt"));
                double[][] didi         = split(readTextFile(dirName + "/dataset/didi.txt"));
                double[][] helloBike    = split(readTextFile(dirName + "/dataset/hello_bike.txt"));
                double[][] nikeRun      = split(readTextFile(dirName + "/dataset/nike_run.txt"));

                insert("baidu",baidu);
                insert("didi",didi);
                insert("helloBike",helloBike);
                insert("nikeRun",nikeRun);
                new AlertDialog.Builder(MainActivity.this).setTitle("提示").setMessage("创建成功咯!").setPositiveButton("确定",null).show();

                merge();

            }
        });

        // 画图测试
        Button paint_button = findViewById(R.id.paintButton);
        paint_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String query = "SELECT x AS x, y AS y FROM" + unionPathName + " WHERE helper = 20;";
                Toast.makeText(MainActivity.this, "You clicked paint Button", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this, PaintT.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("unionPath", trans.genUnion(query));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }
    protected void onStop(){
        Intent intent = new Intent(MainActivity.this,MusicServer.class);
        stopService(intent);
        super.onStop();
        Log.e("main", "...onstop");
    }

    protected void onStart(){
        super.onStart();
        startService(this.music);
        Log.e("main","...onstart");
    }

    //点击exit_button退出程序
    public void showexitdialog(View v){
        //定义一个新对话框对象
        AlertDialog.Builder exit_dialog = new AlertDialog.Builder(this);
        //设置对话框提示内容
        exit_dialog.setMessage("Do you want to save it before exiting the program?");
        //定义对话框两个按钮及接受事件
        exit_dialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //保存
                trans.SaveAll();
                //退出
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        });
        exit_dialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //退出
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        });
        //创建并显示对话框
        AlertDialog exit_dialog0 = exit_dialog.create();
        exit_dialog0.show();

    }

    // 从 path 中读取文件
    private String readTextFile(String path) {
        String res = new String();
        try (FileReader reader = new FileReader(path);
             BufferedReader br = new BufferedReader(reader) // 建立一个对象，它把文件内容转成计算机能读懂的语言
        ) {
            String line;
            while ((line = br.readLine()) != null) {
                res = res + line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res.replace("\r|\n", "");
    }
    // 分割
    private double[][] split(String txt) {
        String[]  pos = txt.substring(1,txt.length()-1)
                .replace("[", "")
                .replace("]", "")
                .split(",");

        double[][] ret = new double[pos.length/2][2];
        for (int i=0;i<pos.length;++i) {
            ret[i/2][i&1] = Double.parseDouble(pos[i]);
        }
        return ret;
    }
    // trans
    private void insert(String classname, double[][] data) {
        trans.query("CREATE CLASS "+ classname + " (x int,y int, helper int);");
        Log.d("Create Class:" , classname);
        for (int i=0;i<data.length;++i) {
            trans.query("INSERT INTO"+ classname + " VALUES(" + data[i][0] + "," +data[i][1]+"," + 20 + " );");
        }
    }
    // merge
    private void merge() {
        trans.query("CREATE UNIONDEPUTY "+ unionPathName + " (\n" +
                "SELECT x AS x, y AS y,helper AS helper FROM baidu WHERE helper = 20\n" +
                "UNION\n" +
                "SELECT x AS x, y AS y,helper AS helper FROM didi WHERE helper = 20\n" +
                "UNION\n" +
                "SELECT x AS x, y AS y,helper AS helper FROM helloBike WHERE helper = 20\n" +
                "UNION\n" +
                "SELECT x AS x, y AS y,helper AS helper FROM nikeRun WHERE helper = 20\n" +
                ");");
    }
}
